﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Common;

namespace DataAccessLayer.DAL
{
    public class ManagerDAL
    {
        public static bool AddProductCategory(ProductCategory pro)
        {
            using (var context = new ReverseAuctionEntities())
            {
                pro.Depth = getDepthProductParent(pro.ParentID) + 1;
                context.ProductCategories.AddObject(pro);
                context.SaveChanges();
                return true;
            }
        }

        public static bool UpdateProductCategory(ProductCategory pro)
        {
            using (var context = new ReverseAuctionEntities())
            {
                var product = context.ProductCategories.SingleOrDefault(u => u.ID==pro.ID);
                product.Name = pro.Name;
                product.Description = pro.Description;
                product.ParentID = pro.ParentID;
                context.SaveChanges();
            }
            return true;
        }

        public static bool DeleteProductCategory(int id)
        {
            using (var context = new ReverseAuctionEntities())
            {
                ProductCategory pro = context.ProductCategories.SingleOrDefault(u => u.ID == id);
                pro.Active = (int)ProductCategoryStatus.Deleted;
                
                context.SaveChanges();
            }
            return true;
        }

        public static int? getDepthProductParent(int? idProduct)
        {
            int? id = null;
            using (var context = new ReverseAuctionEntities())
            {
                ProductCategory pro = context.ProductCategories.SingleOrDefault(u => u.ID == idProduct);
                if (pro != null)
                {
                    id = pro.Depth;
                }
            }

            return id;
        }

        public static List<ProductCategory> GetAllCategories()
        {
            List<ProductCategory> list = null;
            using (var context = new ReverseAuctionEntities())
            {
                String sql = "it.Active=="+ (int)ProductCategoryStatus.Active;
                list = context.ProductCategories.Where(sql).OrderBy("it.Depth").ToList();
            }
            return list;
        }

        public static ProductCategory GetByID(int id)
        {
            using (var context = new ReverseAuctionEntities())
            {
                return context.ProductCategories.SingleOrDefault(u => u.ID == id);
            }
        }
    }
}
